﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using e.Store.Domain;
using e.Store.Domain.Repositories;
using e.Store.Model.Entities;

namespace e.Store.Web.Controllers
{
    public class BillingController : Controller
    {
        //
        // GET: /Billing/

        IUnitOfWork _IUWork;

        public BillingController()
        {
            _IUWork = new UnitOfWorkcs();
        }

        public BillingController(IUnitOfWork _IUnit)
        {
            _IUWork = _IUnit;
        }


        public ActionResult Index()
        {
            return View();
        }


        #region MANAGE SALES
        public ActionResult Sales()
        {
            return View();
        }


        public ActionResult MakeInvoice()
        {

            ViewBag.UserName = "Admin"; // get some session
            ViewBag.TodayDate = DateTime.Now.ToString();

            ProductRepository proRepo = _IUWork.ExtRepositoryFor<ProductRepository>();

            List<GetInvoiceDetailsResult> lstDetails = new List<GetInvoiceDetailsResult>();

            // ---------------- CUSTOMER
            Customer cust = _IUWork.Repository<Customer>().Query().Get().FirstOrDefault();

            if (cust != null)
                ViewBag.CustomerName = cust.CustomerName;
            else
                ViewBag.CustomerName = "Walkin Customer";

            //----------------- INVOICE 
            long userOID = 1; // get value from session
            Invoice inv = _IUWork.Repository<Invoice>().Query().Get().Where(c => c.CreatedBy == userOID && c.IsFinalized == false).FirstOrDefault();
            if (inv != null)
            {
                ViewBag.InvoiceNo = inv.InvoiceNo;
                ViewBag.InvoiceOID = inv.InvoiceOID.ToString();

                lstDetails = proRepo.GetInvoiceDetails(inv.InvoiceOID);
            }
            else
            {
                string newInvoiceNo = GenerateInvoiceNo();

                Invoice newInvoice = new Invoice();
                newInvoice.IsFinalized = false;
                newInvoice.TaxAmount = 0;
                newInvoice.AmoundPaid = 0;
                newInvoice.AmountPayable = 0;
                newInvoice.CreatedBy = userOID;
                newInvoice.CreatedDate = DateTime.Now;
                newInvoice.CustomerOID = cust.CustomerOID;
                newInvoice.InvoiceNo = newInvoiceNo;

                _IUWork.Repository<Invoice>().Insert(newInvoice);
                _IUWork.Save();

                ViewBag.InvoiceNo = newInvoice.InvoiceNo;
                ViewBag.InvoiceOID = newInvoice.InvoiceOID.ToString();
            }

            // step 1 : get or generate the invoice no based on user OID
            // step 2 : load the invoice details based on invoice no and user OID

            //ProductRepository proRepo = _IUWork.ExtRepositoryFor<ProductRepository>();
            //List<ProductDetail> lstDetails = proRepo.LoadAllProductDetails();

            return View(lstDetails);
        }


        private string GenerateInvoiceNo()
        {
            string invoiceNo = DateTime.Now.ToString("MMM", CultureInfo.InvariantCulture).ToUpper()
                                + DateTime.Now.ToString("yy", CultureInfo.InvariantCulture)
                                + "-" + DateTime.Now.ToString("dd", CultureInfo.InvariantCulture);

            try
            {
                long maxInvoiceOID = _IUWork.Repository<Invoice>().Query().Get().Max(c => c.InvoiceOID);

                invoiceNo = invoiceNo + "-" + (maxInvoiceOID + 1).ToString();
            }
            catch (Exception)
            {
            }

            return invoiceNo;
        }

        [HttpPost]
        public JsonResult AddItemToInvoice(string productCode, string invoiceOID)
        {
            bool flag = false;
            string message = "";
            long invOID = Convert.ToInt64(invoiceOID);
            try
            {
                ProductDetail objPro = _IUWork.Repository<ProductDetail>().Query().Get().Where(c => c.ProductCode.Trim().ToLower() == productCode.Trim().ToLower()).FirstOrDefault();

                if (objPro != null)
                {
                    flag = true;

                    InvoiceDetail objInvoiceDetail = null;

                    objInvoiceDetail = _IUWork.Repository<InvoiceDetail>().Query().Get().Where(c => c.ProductOID == objPro.ProductOID && c.InvoiceOID == invOID).FirstOrDefault();
                    if (objInvoiceDetail != null)
                    {
                        objInvoiceDetail.Quantity = objInvoiceDetail.Quantity + 1;
                        objInvoiceDetail.ProductTotalPrice = objInvoiceDetail.Quantity * objInvoiceDetail.PricePerPiece;
                        // calculate tax and discount accordingly

                        _IUWork.Repository<InvoiceDetail>().Update(objInvoiceDetail);
                        _IUWork.Save();
                    }
                    else
                    {
                        objInvoiceDetail = new InvoiceDetail();
                        objInvoiceDetail.CreatedBy = 1; // get from session
                        objInvoiceDetail.CreatedDate = DateTime.Now;
                        objInvoiceDetail.InvoiceOID = invOID;
                        objInvoiceDetail.PricePerPiece = objPro.SellingPrice;
                        objInvoiceDetail.ProductOID = objPro.ProductOID;
                        objInvoiceDetail.ProductTax = objPro.SalesTax; // calculate tax
                        objInvoiceDetail.ProductDiscount = objPro.Discount; // calculate discount
                        objInvoiceDetail.Quantity = 1;
                        objInvoiceDetail.ProductTotalPrice = objInvoiceDetail.Quantity * objInvoiceDetail.ProductTotalPrice; // calculate tax + discuount + price

                        _IUWork.Repository<InvoiceDetail>().Insert(objInvoiceDetail);
                        _IUWork.Save();
                    }

                }
                else
                {
                    flag = false;
                    message = "Invalid product code. Please try again with correct code.";
                }
            }
            catch (Exception)
            {
                TempData["Result"] = "Error!:Please try later! An error has occurred while processing your request.";
            }

            return Json(new { Result = flag, Message = message }, JsonRequestBehavior.AllowGet);
        }




        #endregion

    }
}
